<?php

namespace Beerus\Modules\Designer\Controllers;

use App\Pockets\GridDataModel as pGridDataModel;
use App\Http\Controllers\Controller;
use Doraemon\model\Designer as DesignerModel;
use Doraemon\model\Designer\DesignerEquity;
use Doraemon\model\DesignerTeam;
use Doraemon\model\KaDesigner;
use Doraemon\model\Member;
use Encore\Admin\Grid\Displayers\DropdownActions;
use Frieza\Modules\Position\Actions\CancelApprove;
use Illuminate\Http\Request;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Tab;
use Illuminate\Support\MessageBag;
use Encore\Admin\Widgets\Form;
use Doraemon\service\User;
use Doraemon\model\Es\Designer;
use Doraemon\model\DesignerAuth;
use Beerus\Modules\DesignerList\Actions\ChangeMainArea;
use Doraemon\model\DesignerAdv;
use Beerus\Modules\Designer\Actions\DelAdvPosition;

/**
 * 设计师广告位列表
 *
 * @category   Module name
 * @package    PSR
 * @subpackage Documentation\API
 * @author     hujingdong  <hujingdong@haohaozhu.com>
 * @license    GPL http://www.haohaozhu.com
 * @link       http://www.haohaozhu.com
 */

class AdvPositionController extends Controller
{
    const PAGE_SIZE = 20;


    const CITIES = [
        '北京',
        '上海',
        '广州',
        '深圳',
        '杭州',
        '成都',
        '南京',
        '武汉',
        '重庆',
        '苏州',
        '西安',
        '合肥',
        '无锡',
        '常州',
        '长沙',
    ];

    // 排名
    const RANK = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];


    public function index(Request $request, Content $content)
    {

        $request_data = $request->all();
        $page_size = $request->input('per_page', self::PAGE_SIZE);
        $page = $request->input('page', 1);

        $condition['ORDER'] = ['add_time' => 'DESC'];
        $condition['LIMIT'] = [
            ($page - 1) * $page_size,
            $page_size
        ];

        if (!empty($request_data['uid'])) {
            $condition['uid'] = $request_data['uid'];
        }
        $adv_info = DesignerAdv::getAllAdvInfo($condition);

        $user_ids = array_column($adv_info, 'uid');
        $map_user = User::getUsers($user_ids);
        $total = DesignerAdv::count('*');
        $lists = $adv_info;

        $gridModel = new pGridDataModel($lists, $total, [
            'perPage' => $page_size
        ]);
        $gridList = Admin::grid(
            $gridModel,
            function (Grid $grid) use ($gridModel,$map_user) {
                $grid->paginate($gridModel->getPerPage());
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->disableCreateButton();
                $grid->tools(function ($tools) {
                    $url = url('/admin/Designer/adv/create');
                    $button = '<div class="btn-group download" style="margin-right: 10px">
    <a class="btn btn-sm btn-success" title="广告位录入" target="_blank" href="'.$url.'"><i class="fa fa-plus"></i><span class="hidden-xs">广告位录入</span></a>
</div>';
                    $tools->append($button);
                });
                $grid->setActionClass(DropdownActions::class);

                $grid->filter(function (Grid\Filter $filter) {
                    $filter->disableIdFilter();
                    $filter->column(1 / 2, function ($filter) {
                        $filter->equal('uid', '用户UID')->placeholder('请输入uid');
                    });
                    $filter->expand();
                });

                $grid->column('id', 'id');
                $grid->column('uid', '设计师uid');
                $grid->column('nick', '昵称')->display(function () use ($map_user) {
                    return empty($map_user[$this->uid]['nick']) ? '' : $map_user[$this->uid]['nick'];
                });
                $grid->column("city", '投放城市');
                $grid->column("position", '广告位置')->display(function () {
                    return DesignerAdv::POSITION[$this->position];
                });
                $grid->column("time_period", '投放时间段')->display(function () {
                    $start_date = date('Y-m-d', $this->start_date);
                    $end_date = date('Y-m-d', $this->end_date);
                    return $start_date."-".$end_date;
                });

                $grid->column("show_days", '投放天数')->display(function () {
                    $show_days = ceil(((int)$this->end_date - (int)$this->start_date) / (24 * 3600));
                    return $show_days;
                });
                $grid->column("rank", '排名');
                $grid->column("add_time", '创建时间')->display(function () {
                    return date('Y-m-d H:i:s', $this->add_time);
                });
                $grid->column("edit_time", '修改时间')->display(function () {
                    return date('Y-m-d H:i:s', $this->edit_time);
                });
                $grid->column("admin_name", '处理人');
                $grid->column("remark", '备注');
                $grid->actions(function (Grid\Displayers\Actions $actions) {
                    $actions->disableDelete();
                    $actions->disableView();
                    $actions->add(new DelAdvPosition);
                });
            }
        );

        $tab = new Tab();
        $title = '设计师广告位';
        $tab->add($title, $gridList->render());
        return $content
            ->row($tab)
            ->header($title)
            ->breadcrumb(['text' => $title]);
    }

    public static function edit(Request $request, Content $content, $id = 0){
        $request = $request->all();

        if ($id == 0) {
            $is_create = true;
            $header = '广告位录入';
        } else {
            $is_create = false;
            $header = '编辑广告位信息';
        }

        $tab = new Tab();
        $tab->add('设计师广告位', self::editAction($request, $id, $is_create));
        return $content->header($header)
            ->breadcrumb([
                'text' => '设计师广告位',
                'url' => route('adv.list')
            ], ['text' => $header])->row($tab);
    }

    public static function editAction($request, $id = 0, $is_create = false)
    {
        if ($is_create) {
            $form = new Form([
                'sort' => 1
            ]);
        } else {
            $data = DesignerAdv::get('*', ['id' => $id]);
            $data['start_time'] = date("Y-m-d",$data['start_date']);
            $data['end_time'] = date("Y-m-d",$data['end_date']);
            $data['nick'] = Member::getUser($data['uid'])['nick'];
            $data['city'] = array_search($data['city'],self::CITIES);
            $data['rank'] = array_search($data['rank'],self::RANK);
            $form = new Form($data);
            $form->hidden('id');
        }

        $form->text('uid', '用户uid');
        if ($id){
            $form->text('nick', '用户昵称')->readonly();
        }
        $form->select('position', '广告位置')
            ->setWidth(4, 2)
            ->options(DesignerAdv::POSITION)
            ->default(DesignerAdv::POSITION_FIND_DESIGNER);
        $form->select('city', '投放城市')->setWidth(4, 2)->options(self::CITIES)->default(0);
        $form->date('start_time','起始时间')->format('YYYY-MM-DD');
        $form->date('end_time','结束时间')->format('YYYY-MM-DD');
        $form->select('rank','排名')->setWidth(4, 2)->options(self::RANK);
        $form->textarea('remark', '备注')->setWidth(4, 2);
        $form->action('/admin/Designer/adv/save');

        return $form->render();
    }

    public static function editSubmit(Request $request){
        if (strtotime($request['start_time']) > strtotime($request['end_time'])) {
            $error = new MessageBag([
                'title' => '结束日期不能早于起始日期'
            ]);
            return back()->withInput()->with(compact('error'));
        }

        // 检查起始日期
        if (strtotime($request['start_time']) < strtotime(date('Y-m-d 00:00:00'))) {
            $error = new MessageBag([
                'title' => '投放起始日期必须大于等于当前日期'
            ]);
            return back()->withInput()->with(compact('error'));
        }

        $data = [
            'uid' => $request['uid'],
            'position' => $request['position'],
            'city' => self::CITIES[$request['city']],
            'start_date' => strtotime($request['start_time']),
            'end_date' => strtotime($request['end_time']),
            'rank' => self::RANK[$request['rank']],
            'remark' => $request['remark'],
            'admin_id' => Admin::user()->id,
            'admin_name' => Admin::user()->username,
        ];

        if (isset($request['id'])) {
            $data['edit_time'] = time();
            $rs = DesignerAdv::update($data, [
                'id' => $request['id']
            ]);
        } else {
            $data['add_time'] = time();
            $data['edit_time'] = time();
            $rs = DesignerAdv::insert($data);
        }

        if ($rs) {
            $success = new MessageBag([
                'title' => '操作成功'
            ]);

            return redirect('/admin/Designer/adv/list')->with(compact('success'));
        } else {
            $error = new MessageBag([
                'title' => '操作失败'
            ]);

            return back()->with(compact('error'));
        }
    }

}
